package com.lz.sports.vm.group

import android.text.Editable
import android.text.TextUtils
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lz.library.base.BaseModel
import com.lz.library.base.BaseViewModel
import com.lz.library.extension.showToast
import com.lz.sports.R
import com.lz.sports.bean.DeviceGroup
import com.lz.sports.bean.DeviceInfo
import com.lz.sports.core.ProjectManager
import com.lz.sports.db.DeviceDatabase
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.withContext

//分组绑定
class GroupBindViewModel : BaseViewModel<BaseModel>() {
    //项目ID
    private val projectId = ProjectManager.examProjectId()
    //设备列表
    val deviceInfoList = MutableLiveData<List<DeviceInfo>>()
    //当前组
    var deviceGroup: DeviceGroup? = null
    //搜索关键词
    val keywordStr = MutableLiveData<String>()
    //显示清除
    var showClear = MutableLiveData(false)
    //总数量
    val totalCount = MutableLiveData(0)

    private var listJob: Job? = null

    private var keyword: String? = null

    override fun onCreate(owner: LifecycleOwner) {
        firstPageSearch()
    }

    private fun firstPageSearch() {
        listJob?.cancel()
        listJob = launch {
            flow { emit(DeviceDatabase.get().findUnBindDeviceInfoList(projectId, keyword)) }
                .flowOn(Dispatchers.IO)
                .onStart { updateDialogLoading(true); }
                .onCompletion { updateDialogLoading(false);}
                .collect { deviceInfoList.value = it; totalCount.value = it.size }
        }
    }

    fun search() {
        this.keyword = keywordStr.value?.trim()
        firstPageSearch()
    }

    fun clearSearch() {
        if (!TextUtils.isEmpty(keyword)) {
            keyword = null
            firstPageSearch()
        }
    }

    fun afterTextChanged(editable: Editable) {
        showClear.value = editable.isNotEmpty()
    }

    fun bindItem(deviceInfo: DeviceInfo): Boolean {
        val group = deviceGroup ?: return false
        val number = group.bindDeviceInfo(deviceInfo)
        if (number == DeviceGroup.INVALID_NUMBER) {
            R.string.group_bind_max.showToast()
            return false
        }
        if (number > 0) {
            launch {
                withContext(Dispatchers.Default) {
                    DeviceDatabase.get().bindDeviceGroup(group, deviceInfo.id, number)
                }
                LiveEventBus.get("DeviceGroup_bindDevice", DeviceInfo::class.java).post(deviceInfo)
            }
        }
        return true
    }
}